package com.mikao.service.impl;

import com.mikao.constant.ErrorCode;
import com.mikao.dao.*;
import com.mikao.dto.bo.DoFruitForm;
import com.mikao.dto.bo.DoTreeForm;
import com.mikao.dto.vo.*;
import com.mikao.entity.*;
import com.mikao.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class IndexServiceImpl implements IndexService {

    private RulesDao rulesDao;
    private UserTreeDao userTreeDao;
    private GoodsDao goodsDao;
    private UserSellOrderDao userSellOrderDao;
    private UserDao userDao;
    private OfferPriceDao offerPriceDao;
    private UserBankDao userBankDao;

    public IndexServiceImpl(RulesDao rulesDao, UserTreeDao userTreeDao, GoodsDao goodsDao, UserSellOrderDao userSellOrderDao, UserDao userDao, OfferPriceDao offerPriceDao, UserBankDao userBankDao) {
        this.rulesDao = rulesDao;
        this.userTreeDao = userTreeDao;
        this.goodsDao = goodsDao;
        this.userSellOrderDao = userSellOrderDao;
        this.userDao = userDao;
        this.offerPriceDao = offerPriceDao;
        this.userBankDao = userBankDao;
    }


    @Override
    public BaseResult<PlantDto> index(Long userId) {
        /*
         *  设置攻略
         */

        Rules rules = rulesDao.findAll().get(0);
        PlantDto plantDto = new PlantDto();
        plantDto.setRules(rules.getDetail());

        /*
         *  设置近况
         */
        List<UserTree> list = userTreeDao.findAllByUserIdOrderByCreateTimeDesc(userId);
        if (!ObjectUtils.isEmpty(list)) {
            UserTree userTree = list.get(0);
            if (ObjectUtils.isEmpty(userTree)) {
                return new BaseResult<>(ErrorCode.NULL_CONTENT.getCode(), ErrorCode.NULL_CONTENT.getMsg());
            }
            plantDto.setDetail(userTree.getDetail());

            /*
             * 设置头部文字维护截止期
             */
            Goods goods = goodsDao.findOne(userTree.getGoodsId());
            TreeDto dto = new TreeDto();
            BeanUtils.copyProperties(goods, dto);
            Date createTime = goods.getCreateTime();
            int i = goods.getFirstTime() + goods.getSecondTime() + goods.getThirdTime() + goods.getFourthTime();

            //总时间
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(createTime);
            rightNow.add(Calendar.YEAR, +i);
            Date allTime = rightNow.getTime();

            //已种时间
            long haveTime = userTree.getCreateTime().getTime() - goods.getCreateTime().getTime();
            double l = haveTime * 1.0 / ((allTime.getTime() - goods.getCreateTime().getTime()) * 1.0);
            dto.setProgress(l);
            plantDto.setTreeDtoList(dto);
        }

        /*
         * 设置用户等级
         */
        plantDto.setGrade(list.size());
        return new BaseResult<>(plantDto);
    }

    @Override
    public BaseResult<List<MyTreeDto>> myTree(Long userId) {
        List<UserSellOrder> list = userSellOrderDao.findAllByUserIdAndTypeAndIsPayedOrderByCreateTimeDesc(userId, 1, true);
        List<MyTreeDto> dtos = new ArrayList<>();
        MyTreeDto dto;
        Goods goods;
        long l;
        for (UserSellOrder userSellOrder : list) {
            dto = new MyTreeDto();
            goods = goodsDao.findOne(userSellOrder.getGoodsId());
            dto.setId(userSellOrder.getId());
            dto.setName(goods.getName());
            dto.setGoodsId(goods.getId());
            dto.setStatus(userSellOrder.getStatus());
            l = (userSellOrder.getCreateTime().getTime() - goods.getCreateTime().getTime()) / (1000 * 3600 * 24);
            dto.setDays(l);
            dtos.add(dto);
        }
        return new BaseResult<>(dtos);
    }

    @Override
    public BaseResult<List<FruitDto>> getFruit(Long userId) {
        List<UserTree> list = userTreeDao.findAllByUserIdOrderByCreateTimeDesc(userId);
        List<FruitDto> dtos = new ArrayList<>();
        FruitDto dto;
        Goods goods;
        for (UserTree userTree : list) {
            dto = new FruitDto();
            BeanUtils.copyProperties(userTree, dto);
            goods = goodsDao.findOne(userTree.getGoodsId());
            OfferPrice offerPrice = offerPriceDao.findAllByTypeOrderByCreateTimeDesc(1).get(0);
            dto.setName(goods.getName());
            dto.setRecyclePrice(offerPrice.getPrice());
            dtos.add(dto);
        }
        return new BaseResult<>(dtos);
    }

    @Override
    public BaseResult<WalletDto> wallet(Long userId) {
        User one = userDao.findOne(userId);
        WalletDto walletDto = new WalletDto();
        walletDto.setMoney(one.getMoney());

        //银行卡信息
        UserBank bank = userBankDao.findAllByUserId(userId);
        if (!ObjectUtils.isEmpty(bank)) {
            walletDto.setBankCode(bank.getBankCode());
            walletDto.setBankName(bank.getBankName());
        }
        return new BaseResult<>(walletDto);
    }

    @Override
    public BaseResult doTree(DoTreeForm doTreeForm) {
        UserSellOrder one = userSellOrderDao.findOne(doTreeForm.getId());
        if (!ObjectUtils.isEmpty(one)) {
            //1卖出
            if (doTreeForm.getButton() == 1) {
                //卖给用户
                if (doTreeForm.getType() == 1) {
                    one.setPhone(doTreeForm.getPhone());
                    one.setRecyclePrice(doTreeForm.getRecyclePrice());
                    one.setStatus(4);
                    userSellOrderDao.saveAndFlush(one);
                    return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
                }
                //卖给平台
                if (doTreeForm.getType() == 2) {
                    one.setStatus(1);//待平台报价
                    userSellOrderDao.saveAndFlush(one);
                    return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
                }
            }
            //2处理-确认
            if (doTreeForm.getButton() == 2) {
                one.setStatus(3);
                userSellOrderDao.saveAndFlush(one);
                return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
            }
            //3处理-留下
            if (doTreeForm.getButton() == 3) {
                one.setStatus(6);
                userSellOrderDao.saveAndFlush(one);
                return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
            }
            //4取消出售
            if (doTreeForm.getButton() == 4) {
                one.setStatus(6);
                userSellOrderDao.saveAndFlush(one);
                return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
            }
        }
        return new BaseResult(ErrorCode.NULL_CONTENT.getCode(), ErrorCode.NULL_CONTENT.getMsg());
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public BaseResult doFruit(Long userId, DoFruitForm doFruitForm) {
        UserTree one = userTreeDao.findOne(doFruitForm.getId());
        //卖给商城
        if (doFruitForm.getButton() == 1) {
            if (doFruitForm.getWeight() > one.getWeight()) {
                return new BaseResult(ErrorCode.PARAM_ERROR.getCode(), "售卖重量大于收货重量");
            }
            //减少收获重量
            one.setUserWeight(doFruitForm.getWeight());
            one.setWeight(one.getWeight() - doFruitForm.getWeight());
            userTreeDao.saveAndFlush(one);

            //增加用户收益
            User user = userDao.findOne(userId);
            Double price = offerPriceDao.findAllByTypeOrderByCreateTimeDesc(1).get(0).getPrice();
            user.setMoney(user.getMoney() + price * doFruitForm.getWeight());
            userDao.saveAndFlush(user);

            //新增卖给商城的售卖记录
            UserSellOrder userSellOrder = new UserSellOrder();
            userSellOrder.setType(2);
            userSellOrder.setStatus(1);//待报价
            userSellOrder.setRecyclePrice(offerPriceDao.findOne(Long.valueOf(1)).getPrice());
            userSellOrder.setWeight(doFruitForm.getWeight());
            userSellOrder.setUserId(userId);
            userSellOrder.setGoodsId(one.getGoodsId());
            userSellOrderDao.saveAndFlush(userSellOrder);

            return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
        }
        //卖给植友
        if (doFruitForm.getButton() == 2) {
            //改变商品来源，修改价格重量
            Goods goods = goodsDao.findOne(one.getGoodsId());
            goods.setSource(2);
            goods.setPrice(String.valueOf(doFruitForm.getPrice()));
            goods.setWeight(doFruitForm.getWeight());
            goodsDao.saveAndFlush(goods);

            //减少所剩重量
            one.setUserWeight(doFruitForm.getWeight());
            one.setWeight(one.getWeight() - doFruitForm.getWeight());
            userTreeDao.saveAndFlush(one);

            //新增售卖订单
            UserSellOrder userSellOrder = new UserSellOrder();
            userSellOrder.setType(3);
            userSellOrder.setStatus(4);//挂单
            userSellOrder.setRecyclePrice(doFruitForm.getPrice());
            userSellOrder.setWeight(doFruitForm.getWeight());
            userSellOrder.setUserId(userId);
            userSellOrder.setGoodsId(one.getGoodsId());
            userSellOrderDao.saveAndFlush(userSellOrder);

            return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
        }
        return new BaseResult(ErrorCode.PARAM_ERROR.getCode(), ErrorCode.PARAM_ERROR.getMsg());
    }

    @Override
    public BaseResult<Integer> myTreeCount(Long userId) {
        return new BaseResult(userTreeDao.findAllByUserIdOrderByCreateTimeDesc(userId).size());
    }
}
